<template>
	<view class="">
		<view class="title-box">
			<u-cell-group :border="false">
				<u-cell-item :border-bottom="false" :border-top="false" :arrow="false"
					:title-style="{fontSize:'40rpx',fontWeight:700,color:'#000'}">
					<text class="but-right">停车记录</text>
				</u-cell-item>
			</u-cell-group>
		</view>
		<view style="background-color: #fff;">
			<view style="width: 400rpx;">
				<u-tabs :list="list" :is-scroll="false" :current="current" @change="change"></u-tabs>
			</view>
		</view>
		<view class="bill one" v-if="current==0">
			<view class="addCar" @click="openAddPlate"></view>
			<view class="not" v-for="(item,index) in cardList" :key="index">
				<view>
					<view class="car">{{item.licensePlate}}</view>
					<view>房产：{{item.houseNumberInfo}}</view>
				</view>
				<view class="delete">
					<u-tag style="width: 120rpx;text-align: center;"
						:text="$dictTools.dictTypeData('LICENSE_PLATE_COLOR',item.licensePlateColor)" size="mini"
						:type="$dictTools.fileTag('LICENSE_PLATE_COLOR',item.licensePlateColor)"></u-tag>
					<u-icon class="icon" name="trash-fill" label="删除" @click="submit(index)"></u-icon>
				</view>
			</view>
		</view>
		<view class="bill tow" v-else>
			<u-form :model="form" ref="uForm" :labelWidth="160" :label-style="{'paddingLeft':'30rpx'}">
				<view class="item-box">
					<u-form-item label="当前房产" prop="roomId" :border-bottom="false">
						<view @tap="selectBol.roomId=true" class="wd-100">
							<u-section :title="property || '请选择'" color="#4A7ED7" :show-line="false"  :bold="false"
								:sub-title="null"></u-section>
							<u-select v-model="selectBol.roomId" :list="seleVisit" @confirm="selctConfirm($event,'roomId',true)"></u-select>
						</view>
					</u-form-item>
				</view>
			<view class="not" v-for="(item,index) in drivewayList" :key="index">
				<view>
					<view>车位所属楼宇：{{item.buildingInfo}}</view>
					<view>区域：{{item.area}}</view>
					<view>车位号：{{item.parkingNo}}</view>
					<u-tag style="width: 120rpx;text-align: center;"
						:text="$dictTools.dictTypeData('USE_TYPE',item.useType)" size="mini"
						:type="$dictTools.fileTag('USE_TYPE',item.useType)"></u-tag>
				</view>
			</view>
			</u-form>
		</view>
	</view>
</template>

<script>
	import {
		householdinfo
	} from '@/api/base/householdinfoApi.js'
	import {
		vehicleManagePage,vehicleManageDelete
	} from '@/api/wit/vehicleManageApi.js'
	
	import {
		parkingSpacePage
	} from '@/api/base/parkingSpaceApi.js'
	
	import { mapGetters } from 'vuex'
	
	export default {
		data() {
			return {
				dateTime: '2023-05',
				params: {
					year: true,
					month: true,
					day: false,
					hour: false,
					minute: false,
					second: false
				},
				show: false,
				list: [{
					name: '车辆'
				}, {
					name: '车位'
				}],
				current: 0,
				cardList: [],
				drivewayList: [],
				parameter:{
					current: 1,
					size: 10
				},
				allDataLoaded: false,
				property: '',
				form: {
					roomId: ''
				},
				seleVisit: [],
				selectBol: {
					roomId: false
				},
			}
		},
		mounted() {
		    this.loadData()
		  },
		computed: {
		    ...mapGetters(['user_info']),
		  },
		methods: {
			//获取当前房产
			currentProperty() {
			    const proprietorId = this.user_info.id;
					console.log(this.user_info,'this.user_info')
			    householdinfo({ proprietorId })
			      .then(response => {
			       const newSelectData = response.map(data => ({
			           value: data.roomId, 
			           label: data.roomInfo
			         }));
			
			        this.seleVisit = newSelectData 
					//默认第一个房产信息显示
					this.form.roomId = newSelectData[0].value
					this.property = newSelectData[0].label 
						console.log(this.seleVisit,'this.seleVisit');
			      })
			      .catch(error => {
			        console.error('获取当前房产失败', error);
			      });
			  },
			async change(index) {
			  this.current = index;
			  this.parameter.current = 1;  // 重置current为1
			  this.cardList = []; // 清空cardList
			  this.drivewayList = []; // 清空drivewayList
			  if (index === 0) { // 车辆选项
			        await this.loadData();
			    } else if (index === 1) {
					if (this.seleVisit.length === 0) {
						this.currentProperty();
					} else {
						this.drivewayData();
					}
				}
			},
			//车辆数据
			async loadData() {
			     try {
					const proprietorId = this.user_info.id
					const parmas = {...this.parameter}
					
					const response = await vehicleManagePage({...parmas,proprietorId:proprietorId})
					
					if (response.records.length > 0) { // 如果有数据
					          this.cardList = this.cardList.concat(response.records) //数据全部连接到一起
					          this.parameter.current++ //拿到全部分页
					        } else {
					          this.allDataLoaded = true;  // 数据已经全部加载完
					    }
			     } catch (error) {
			       console.error('error', error)
			     }
			},
			//车位数据
			async drivewayData() {
			    try {
			        const parmas = { ...this.parameter };
			        const response = await parkingSpacePage({ ...parmas, roomId: this.form.roomId });
			
			        if (response.records.length > 0) {
			            this.drivewayList = response.records;
			            this.$nextTick(() => {
			                console.log('Driveway data updated:', this.drivewayList);
			            });
			        } else {
			            this.drivewayList = []; // 清空数据
			            this.$nextTick(() => {
			                console.log('Driveway list is empty.');
			            });
			        }
			    } catch (error) {
			        console.error('Error fetching driveway data:', error);
			    }
			},
			submit(index) {
			    uni.showModal({
			      title: '提示',
			      content: '确定要删除吗？',
			      success: (res) => {
			        if (res.confirm) {
			          vehicleManageDelete([{ id: this.cardList[index].id }])
			            .then(res => {
							this.parameter.current = 1;
							this.cardList = [];
							this.loadData();
			            });
			        }
			      }
			    })
			},
			openAddPlate(){
				uni.navigateTo({
					url:'/subPack/addPlate'
				})
			},
			onReachBottom() {
				if (!this.allDataLoaded) {  // 如果数据还没有全部加载完才继续加载
				    this.loadData()
				    this.drivewayData()
				}
			},
			selctConfirm(e, type, isVisitorAim) {
				this.form[type] = e[0].value;
				this.property = e[0].label;
			},
		},
		watch: {
		    'form.roomId': function(newRoomId, oldRoomId) {
		        if (newRoomId !== oldRoomId && this.current === 1) {
		            this.$set(this.form, 'roomId', newRoomId);
		            this.drivewayData();
		        }
		    }
		}
	}
</script>

<style lang="scss" scoped>
	/deep/.u-divider{
		background-color: transparent !important;
	}
	/deep/.u-cell{
		padding: 0 32rpx 0 0 !important;
	}
	.addCar{
		width: 95%;
		height: 180rpx;
		margin: 30rpx auto;
		
		background: url('https://oss.hntenghu.com/wuye/wy_17.png')  no-repeat;
		background-size: cover;
	}
	.but-right {
		border: 1px solid $-color-but-wy;
		color: $-color-but-wy;
		border-radius: 50rpx;
		text-align: center;
		padding: 7rpx 20rpx;
	}
	.bill {
		&.tow {
			.selct {
				margin: 20rpx 30rpx;
				font-weight: 700;
			}
		}

		.not {
			display: flex;
			justify-content: space-between;
			border-radius: 8px;
			padding: 15px 25px 0 25px;
			box-shadow: none;
			background: #e5e5e547;
			margin: 10px 10px 0 10px;
			color: #353535b0;
			.car{
				font-size: 16px;
				color: #000;
				font-weight: 700;
			}
			.delete{
				display: flex;
				flex-direction: column; 
				align-items: center;
				.icon{
					margin-top: 6px;
				}
			}
			view{
				margin-bottom: 10px;
			}
		}
	}
	/deep/.u-section__right-info__icon-arrow {
	    margin-right: 12px;
	}
</style>